package hu.myai.controller;

import hu.myai.util.SanfordNet;

import java.util.ArrayList;
import java.util.List;

import org.joone.log.ILogger;
import org.joone.log.LoggerFactory;
import org.joone.net.NeuralNet;

public class InitAndTrainNetwork {

	private static final ILogger log = LoggerFactory.getLogger(InitAndTrainNetwork.class);

	public InitAndTrainNetwork() {
	}

	public void go(String symbol) {

		NeuralNet myNet = null;
		SanfordNet netUtil = new SanfordNet();

		// if not even one given over, it makes it all
		List<String> symbolList = new ArrayList<String>();
		if ("".equals(symbol))
			symbolList = netUtil.getAllSymbol();
		else
			symbolList.add(symbol);

		InitNetwork initClass = new InitNetwork();
		InitNetwork.InitNet initNet = initClass.new InitNet();

		// init with the first item
		String symbol1 = symbolList.get(0);
		log.info("Init symbol: " + symbol1);
		initNet.go(symbol1, 400, 400, 400);
		initNet.nnet.join();
		myNet = initNet.nnet.cloneNet();
		log.info("Init done: " + symbol1);

		symbolList.remove(0);

		TrainNetwork trainClass = new TrainNetwork();
		// TrainNetwork.TrainNet trainNet = trainClass.new TrainNet(myNet);
		while (true) {
			for (String symbolItem : symbolList) {

				try {
					log.info("Train symbol: " + symbolItem);
					TrainNetwork.TrainNet trainNet = trainClass.new TrainNet(myNet);

					trainNet.go(symbolItem);
					trainNet.nnet.join();

					trainNet.nnet.stop();

					trainNet.nnet.getMonitor().setExporting(true);
					myNet = trainNet.nnet.cloneNet();
					trainNet.nnet.getMonitor().setExporting(false);

					netUtil.saveNeuralNet(trainNet.nnet, symbol + "_backup.snet");
					log.debug("Saved " + symbol + ": " + trainNet.nnet.getMonitor().getGlobalError());

				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}
	}
}
